import { createRouter, createWebHistory } from 'vue-router'
import LoginPage from '@/views/login/LoginPage.vue'
import LayoutContainer from '@/views/layout/LayoutContainer.vue'
import ArticleManage from '@/views/article/ArticleManage.vue'
import ArticleChannel from '@/views/article/ArticleChannel.vue'
import UserProfile from '@/views/user/UserProfile.vue'
import UserAvatar from '@/views/user/UserAvatar.vue'
import UserPassword from '@/views/user/UserPassword.vue'
import { useUserStore } from '@/stores/user.js'
// createRouter 创建路由实例，===> new VueRouter()
// 1. history模式: createWebHistory()   http://xxx/user
// 2. hash模式: createWebHashHistory()  http://xxx/#/user

// vite 的配置 import.meta.env.BASE_URL 是路由的基准地址，默认是 ’/‘
// https://vitejs.dev/guide/build.html#public-base-path

// 如果将来你部署的域名路径是：http://xxx/my-path/user
// 就需要在vite.config.ts  添加配置  base: my-path，路由这就会加上 my-path 前缀了
// createRouter用于创建路由实例
const router = createRouter({
  // 等于在Vue2中的：mode:history
  // import.meta.env.BASE_URL默认前缀："/"
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginPage
    },
    {
      path: '/',
      name: 'layout',
      component: LayoutContainer,
      // 当访问到/路径时，我们默认重定向到文章管理页面
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          name: 'manage',
          component: ArticleManage
        },
        {
          path: '/article/channel',
          name: 'channel',
          component: ArticleChannel
        },
        {
          path: '/user/profile',
          name: 'profile',
          component: UserProfile
        },
        {
          path: '/user/avatar',
          name: 'avatar',
          component: UserAvatar
        },
        {
          path: '/user/password',
          name: 'password',
          component: UserPassword
        }
      ]
    }
  ]
})
// 登录访问拦截
router.beforeEach((to) => {
  const userStore = useUserStore()
  // 如果没有token，并且访问的路径不是/login，则需要跳转到登录页
  if (!userStore.token && to.path !== '/login') return '/login'
})

export default router
